package com.regis.comment.aop;

import com.regis.comment.GlobalException;
import com.regis.comment.CodeMsg;
import com.regis.entity.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.BindException;
import java.util.List;

/**
 * @author 计算机系 ITAEM 纱雾休比我老婆
 * @Description 全局异常处理
 * @date 2022/5/15 19:26
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})//捕捉范围
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResultVo<String> exceptionHandler(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        log.error(e.toString());
        if (e instanceof GlobalException) {//自定义的异常
            return ResultVo.error(((GlobalException) e).getCodeMsg());
        } else if (e instanceof BindException) {
            org.springframework.validation.BindException ex = (org.springframework.validation.BindException) e;
            List<ObjectError> errors = ex.getAllErrors();//绑定错误返回很多错误，是一个错误列表，只需要第一个错误
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return ResultVo.error(CodeMsg.PARAMETER_ERROR.fillArgs(msg));//给状态码填充参数
        } else if (e instanceof DuplicateKeyException) {//sql异常，关于值重复
            if(e.getMessage().contains("Duplicate entry")) {
                String[] split = e.getMessage().split(" ");
                String msg = split[split.length - 4] + "已存在";
                return ResultVo.error(msg);
            }
            return ResultVo.error("未分类的sql异常");
        } else {
            return ResultVo.error(CodeMsg.SERVICE_ERROR);
        }
    }
}
